<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock, Message, Eleme } from '@element-plus/icons-vue'
import {useUserStore} from "@/stores/index.js";
import { userAPI } from '@/apis/user.js';

// 定义emit事件
const emit = defineEmits(['openLogin', 'openExternalRegister'])

// 控制对话框显示
const dialogVisible = ref(false)

const userStore = useUserStore()

// 表单数据
const registerForm = reactive({
  nickName: '',
  email: '',
  password: '',
  confirmPassword: '',
  verificationCode: ''
})

// 确认密码验证
const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('Please confirm your password'))
  } else if (value !== registerForm.password) {
    callback(new Error('The two passwords do not match'))
  } else {
    callback()
  }
}

// 表单验证规则
const rules = {
  nickName: [
    { required: true, message: 'Please input username', trigger: 'blur' },
    { min: 3, max: 20, message: 'The username length ranges from 3 to 20 characters', trigger: 'blur' }
  ],
  email: [
    { required: true, message: 'Please input email', trigger: 'blur' },
    { type: 'email', message: 'Please input a valid email address', trigger: 'blur' }
  ],
  password: [
    { required: true, message: 'Please input the password', trigger: 'blur' },
    { min: 6, max: 20, message: 'Password length is between 6 and 20 characters', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: 'Please confirm your password', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: 'Please input verification code', trigger: 'blur' },
    { len: 6, message: 'Verification code must be 6 digits', trigger: 'blur' }
  ]
}

// 表单引用
const registerFormRef = ref()

// 注册加载状态
const loading = ref(false)

// 验证码相关状态
const sendingCode = ref(false)
const countdown = ref(0)
const countdownTimer = ref(null)

// 打开注册对话框
const openRegisterDialog = () => {
  dialogVisible.value = true
}

// 关闭注册对话框
const closeDialog = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  if (registerFormRef.value) {
    registerFormRef.value.resetFields()
  }
  registerForm.nickName = ''
  registerForm.email = ''
  registerForm.password = ''
  registerForm.confirmPassword = ''
  registerForm.verificationCode = ''
  
  // 清除倒计时
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
    countdownTimer.value = null
  }
  countdown.value = 0
}

// 发送验证码
const sendVerificationCode = async () => {
  // 先验证邮箱格式
  if (!registerForm.email) {
    ElMessage.error('Please input email first')
    return
  }
  
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(registerForm.email)) {
    ElMessage.error('Please input a valid email address')
    return
  }
  
  try {
    sendingCode.value = true
    
    const response = await userAPI.sendVerificationCode({
      email: registerForm.email
    })
    
    if (response && response.status === 'success') {
      ElMessage.success('Verification code sent successfully')
      
      // 开始倒计时
      countdown.value = 60
      countdownTimer.value = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(countdownTimer.value)
          countdownTimer.value = null
        }
      }, 1000)
    }
  } catch (error) {
    console.log(error)
  } finally {
    sendingCode.value = false
  }
}

// 注册提交
const handleRegister = async () => {
  if (!registerFormRef.value) return

  try {
    const valid = await registerFormRef.value.validate()
    if (valid) {
      loading.value = true

      // 调用userStore的注册方法
      const response = await userStore.register({
        email: registerForm.email,
        nickname: registerForm.nickName,
        password: registerForm.password,
        verificationCode: registerForm.verificationCode
      })
      // 注册成功
      if (response && response.status === 'success') {
        closeDialog()
        // 触发父组件打开登录对话框
        emit('openLogin')
      }
    }
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }

}

// 跳转到外部用户注册页面
const goToExternalRegister = () => {
  closeDialog()
  // 触发父组件打开外部用户注册对话框
  emit('openExternalRegister')
}

// 暴露方法给父组件调用
defineExpose({
  openRegisterDialog
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    width="420px"
    :before-close="closeDialog"
    :show-close="false"
    class="register-dialog"
    center
  >
    <template #header>
      <div class="register-header">
        <span>User Registration</span>
      </div>
    </template>
    <el-form
      ref="registerFormRef"
      :model="registerForm"
      :rules="rules"
      class="register-form"
    >
      <el-form-item prop="username">
        <el-input
          v-model="registerForm.nickName"
          placeholder="Please input username"
          :maxlength="150"
          clearable
          size="large"
          :prefix-icon="User"
        />
      </el-form-item>
      
      <el-form-item prop="email">
        <el-input
          v-model="registerForm.email"
          placeholder="Only campus email can be registered"
          :maxlength="150"
          clearable
          size="large"
          :prefix-icon="Message"
        />
      </el-form-item>
      
      <el-form-item prop="verificationCode">
        <div class="verification-code-container">
          <el-input
            v-model="registerForm.verificationCode"
            placeholder="Please input verification code"
            :maxlength="6"
            clearable
            size="large"
            class="verification-input"
            :prefix-icon="Eleme"
          />
          <el-button
            @click="sendVerificationCode"
            :loading="sendingCode"
            :disabled="countdown > 0"
            size="large"
            class="send-code-btn"
          >
            {{ countdown > 0 ? `${countdown}s` : 'Send Code' }}
          </el-button>
        </div>
      </el-form-item>
      
      <el-form-item prop="password">
        <el-input
          v-model="registerForm.password"
          type="password"
          placeholder="Please input password"
          show-password
          :maxlength="150"
          clearable
          size="large"
          :prefix-icon="Lock"
        />
      </el-form-item>
      
      <el-form-item prop="confirmPassword">
        <el-input
          v-model="registerForm.confirmPassword"
          type="password"
          placeholder="Please confirm password"
          show-password
          :maxlength="150"
          clearable
          size="large"
          :prefix-icon="Lock"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <div class="external-register-link">
          <span>External user?</span>
          <el-button type="text" @click="goToExternalRegister">External User Registration</el-button>
        </div>
        <div class="button-group">
          <el-button @click="closeDialog">Cancel</el-button>
          <el-button
            type="primary"
            @click="handleRegister"
            :loading="loading"
          >Register</el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.register-header {
  font-size: 24px;
}

.register-form {
  .el-form-item {
    margin-bottom: 24px;
  }
  
  .verification-code-container {
    display: flex;
    gap: 10px;
    width: 100%;

    .verification-input {
      flex: 1;
    }
    
    .send-code-btn {
      width: 100px;
    }
  }
}

.dialog-footer {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  gap: 16px;

  .external-register-link {
    text-align: left;
    color: #666;
    font-size: 14px;

    span {
      margin-right: 4px;
    }

    .el-button {
      padding: 0;
      font-size: 14px;
      color: #409EFF;

      &:hover {
        color: #66b1ff;
      }
    }
  }

  .button-group {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    gap: 5px;
  }
}
</style>